//
//  NewsASRViewController.m
//  suRead
//
//  Created by lidi on 2018/6/5.
//  Copyright © 2018年 bao. All rights reserved.
//

#import "NewsASRViewController.h"
#import "BDSEventManager.h"
#import "BDSASRDefines.h"
#import "BDSASRParameters.h"
#import "Waver.h"

//#error 请在官网新建app，配置bundleId，并在此填写相关参数
NSString * const APP_ID = @"11304278";
NSString * const API_KEY = @"5qGfEQWKKSMGdheResUd0OCs";
NSString * const SECRET_KEY = @"ysHIqb0PCBP8bzG07a5bHLEEEfNRgDyS";

@interface NewsASRViewController ()<BDSClientASRDelegate>
@property (weak, nonatomic) IBOutlet UIButton *buttonClose;
@property (weak, nonatomic) IBOutlet UILabel *labelStatus;
@property (weak, nonatomic) IBOutlet UIButton *buttonRecord;
@property (weak, nonatomic) IBOutlet UIView *maskViewTop;

@property (strong, nonatomic) BDSEventManager *asrEventManager;
@property (weak, nonatomic) IBOutlet UIView *waveView;
@property (strong,nonatomic) Waver *waver;

@property (assign,nonatomic) CGFloat meter;
@end

@implementation NewsASRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor clearColor];
    self.view.userInteractionEnabled = YES;
    [self.buttonClose addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.buttonRecord addTarget:self action:@selector(touchDownAction:) forControlEvents:UIControlEventTouchDown];
    [self.buttonRecord addTarget:self action:@selector(touchUpAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonRecord addTarget:self action:@selector(touchUpAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    self.asrEventManager = [BDSEventManager createEventManagerWithName:BDS_ASR_NAME];
    NSLog(@"Current SDK version: %@", [self.asrEventManager libver]);
    [self configVoiceRecognitionClient];
    
    __weak typeof(self) weakSelf = self;
    self.waver = [[Waver alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), 100.0)];
    [self.waver setWaveColor:[UIColor redColor]];
    self.waver.waverLevelCallback = ^(Waver * waver) {
        CGFloat normalizedValue = pow (10, (weakSelf.meter - 80.0f) / 40.0f);
        waver.level = normalizedValue;
    };
    
    [self.waveView addSubview:self.waver];
    
    UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeAction:)];
    [self.maskViewTop addGestureRecognizer:ges];
    self.maskViewTop.userInteractionEnabled = YES;
}

- (void)closeAction:(id)sender {
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
}

- (void)touchDownAction:(id)sender {
    self.labelStatus.text = @"聆听中";
    //[self.asrEventManager setParameter:@(NO) forKey:BDS_ASR_ENABLE_LONG_SPEECH];
    //[self.asrEventManager setParameter:@(NO) forKey:BDS_ASR_NEED_CACHE_AUDIO];
    //[self.asrEventManager setParameter:@"" forKey:BDS_ASR_OFFLINE_ENGINE_TRIGGERED_WAKEUP_WORD];
    //[self.asrEventManager setParameter:@(YES) forKey:BDS_ASR_VAD_ENABLE_LONG_PRESS];
    
    //[self.asrEventManager setParameter:nil forKey:BDS_ASR_AUDIO_FILE_PATH];
    //[self.asrEventManager setParameter:nil forKey:BDS_ASR_AUDIO_INPUT_STREAM];
    
    [self.asrEventManager sendCommand:BDS_ASR_CMD_START];
}

- (void)touchUpAction:(id)sender {
    self.labelStatus.text = @"按住说话";
    
    self.meter = 0;
    [self.asrEventManager sendCommand:BDS_ASR_CMD_STOP];
}

#pragma mark - BDSClientASRDelegate

- (void)VoiceRecognitionClientWorkStatus:(int)workStatus obj:(id)aObj {
    switch (workStatus) {
        case EVoiceRecognitionClientWorkStatusMeterLevel:
            if ([aObj isKindOfClass:[NSNumber class]]) {
                self.meter = [aObj floatValue];
            }
            break;
        case EVoiceRecognitionClientWorkStatusEnd:
            break;
        case EVoiceRecognitionClientWorkStatusFinish: {
            if (aObj && [aObj isKindOfClass:[NSDictionary class]]) {
                NSArray<NSString *> *results = [aObj objectForKey:@"results_recognition"];
                if (results && [results isKindOfClass:[NSArray<NSString *> class]] && [results count] > 0) {
                    NSString *rs = @"";
                    for (NSInteger i=0; i<[results count]; i++) {
                        NSString *sub = [results objectAtIndex:i];
                        rs = [rs stringByAppendingString:sub];
                    }
                    
                    if (self.handle) {
                        self.handle(rs);
                    }
                    [self closeAction:nil];
                }
            }
            break;
        }
        default:
            break;
    }
    
}

#pragma mark - Private: Configuration

- (void)configVoiceRecognitionClient {
    //设置DEBUG_LOG的级别
    [self.asrEventManager setParameter:@(EVRDebugLogLevelTrace) forKey:BDS_ASR_DEBUG_LOG_LEVEL];
    [self.asrEventManager setDelegate:self];
    //配置API_KEY 和 SECRET_KEY 和 APP_ID
    [self.asrEventManager setParameter:@[API_KEY, SECRET_KEY] forKey:BDS_ASR_API_SECRET_KEYS];
    [self.asrEventManager setParameter:APP_ID forKey:BDS_ASR_OFFLINE_APP_CODE];
    //配置端点检测（二选一）
    [self configModelVAD];
    //      [self configDNNMFE];
    
    //     [self.asrEventManager setParameter:@"15361" forKey:BDS_ASR_PRODUCT_ID];
    // ---- 语义与标点 -----
    [self enableNLU];
    //    [self enablePunctuation];
    // ------------------------
}

- (void) enableNLU {
    // ---- 开启语义理解 -----
    [self.asrEventManager setParameter:@(YES) forKey:BDS_ASR_ENABLE_NLU];
    [self.asrEventManager setParameter:@"1536" forKey:BDS_ASR_PRODUCT_ID];
}

- (void) enablePunctuation {
    // ---- 开启标点输出 -----
    [self.asrEventManager setParameter:@(NO) forKey:BDS_ASR_DISABLE_PUNCTUATION];
    // 普通话标点
    //    [self.asrEventManager setParameter:@"1537" forKey:BDS_ASR_PRODUCT_ID];
    // 英文标点
    [self.asrEventManager setParameter:@"1737" forKey:BDS_ASR_PRODUCT_ID];
}

- (void)configModelVAD {
    NSString *modelVAD_filepath = [[NSBundle mainBundle] pathForResource:@"bds_easr_basic_model" ofType:@"dat"];
    [self.asrEventManager setParameter:modelVAD_filepath forKey:BDS_ASR_MODEL_VAD_DAT_FILE];
    [self.asrEventManager setParameter:@(YES) forKey:BDS_ASR_ENABLE_MODEL_VAD];
}

- (void)configDNNMFE {
    NSString *mfe_dnn_filepath = [[NSBundle mainBundle] pathForResource:@"bds_easr_mfe_dnn" ofType:@"dat"];
    [self.asrEventManager setParameter:mfe_dnn_filepath forKey:BDS_ASR_MFE_DNN_DAT_FILE];
    NSString *cmvn_dnn_filepath = [[NSBundle mainBundle] pathForResource:@"bds_easr_mfe_cmvn" ofType:@"dat"];
    [self.asrEventManager setParameter:cmvn_dnn_filepath forKey:BDS_ASR_MFE_CMVN_DAT_FILE];
    
    [self.asrEventManager setParameter:@(NO) forKey:BDS_ASR_ENABLE_MODEL_VAD];
    // MFE支持自定义静音时长
    //    [self.asrEventManager setParameter:@(500.f) forKey:BDS_ASR_MFE_MAX_SPEECH_PAUSE];
    //    [self.asrEventManager setParameter:@(500.f) forKey:BDS_ASR_MFE_MAX_WAIT_DURATION];
}

- (void)configOfflineClient {
    // 离线仅可识别自定义语法规则下的词
    NSString* gramm_filepath = [[NSBundle mainBundle] pathForResource:@"bds_easr_gramm" ofType:@"dat"];;
    NSString* lm_filepath = [[NSBundle mainBundle] pathForResource:@"bds_easr_basic_model" ofType:@"dat"];;
    NSString* wakeup_words_filepath = [[NSBundle mainBundle] pathForResource:@"bds_easr_wakeup_words" ofType:@"dat"];
    [self.asrEventManager setDelegate:self];
    [self.asrEventManager setParameter:APP_ID forKey:BDS_ASR_OFFLINE_APP_CODE];
    [self.asrEventManager setParameter:lm_filepath forKey:BDS_ASR_OFFLINE_ENGINE_DAT_FILE_PATH];
    // 请在 (官网)[http://speech.baidu.com/asr] 参考模板定义语法，下载语法文件后，替换BDS_ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH参数
    [self.asrEventManager setParameter:gramm_filepath forKey:BDS_ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH];
    [self.asrEventManager setParameter:wakeup_words_filepath forKey:BDS_ASR_OFFLINE_ENGINE_WAKEUP_WORDS_FILE_PATH];
}

@end
